package com.naiterui.ehp.bs.patient.dao.mongo;

import com.naiterui.ehp.bs.patient.vo.consult.Session;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 负责消息数据的持久化和消息数据的获取
 * <p>
 * File name : MessageDao.java
 * </P>
 * <p>
 * Author : zhouyanxin
 * </P>
 * <p>
 * Date : 2015年6月28日
 * </P>
 */
@Repository
@RequiredArgsConstructor
public class ApSessionDao extends MongoBaseDao {

    /**
     * 会话记录的collectionName
     */
    private static final String COLLECTION_NAME = "m_session";
    protected final MongoTemplate mongoTemplate;

    @Override
    protected MongoTemplate getMongoTemplate() {
        return this.mongoTemplate;
    }

    /**
     * 获取最近的一次会话
     */
    public List<Session> queryFirstSession(Long fromId, Long toId) {
        Criteria c1 = Criteria.where("from.id").is(fromId).and("to.id").is(toId);
        Criteria c2 = Criteria.where("from.id").is(toId).and("to.id").is(fromId);
        Criteria c3 = new Criteria().orOperator(c1, c2);
        // 查询
        Query query = Query.query(c3).with(Sort.by(new Sort.Order(Sort.Direction.DESC, "endTime"))).limit(1);
        return super.find(query, Session.class, COLLECTION_NAME);
    }
}
